package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.DisplayBill;
import com.chen.pfm.provider.DisplayBillProvider;
import com.chen.pfm.provider.TitleProvider;
import com.chen.pfm.utils.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ListDialog;
import ohos.app.AbilityContext;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

public class BillManagementSlice extends AbilitySlice {
    private static String CurrentClassName = "BillManagementSlice";
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, CurrentClassName);
    List<DisplayBill> displayBills;
    DisplayBillProvider displayBillProvider;
    ListContainer listContainer;
    Text select_condition;
    Text select_time;
    int selectTimeType;
    int selectSortType;
    DisplayBill item;//触发账单的元素
    int itemPosition;//触发事件的元素项位置
    DisplayBill displayBill;//单一被处理的
    int selectYearIndex;
    int selectMonthIndex;
    String displaytime;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_bills_management);
        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener((component) -> {
            terminate();
        });
        //选择排序条件
        select_condition = (Text) findComponentById(ResourceTable.Id_select_condition);
        //事件监听
        select_condition.setClickedListener(component -> showPickSortType(this));
        //选择排序条件
        select_time = (Text) findComponentById(ResourceTable.Id_select_time);
        //事件监听
        select_time.setClickedListener(component -> showPickTimeType(this));
        // 获取ListContainer
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_bills_ListContainer);
        try {
            displayBills = MyUtil.queryDisplayTotalBill(this);
            Collections.sort(displayBills, new Comparator<DisplayBill>() {
                @Override
                public int compare(DisplayBill o1, DisplayBill o2) {
                    //这里使用时间字段排序 如果要用其他字段直接从bean实体中取
                    return o2.getRecordTime().compareTo(o1.getRecordTime());
                    //上面使用的是降序排序，如果正序 直接使用o1-o2即可
                }
            });
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        if (displayBills == null) {
            HiLog.error(LABEL, "收支账单染数据为空！");
            MyToast.showMyToast(this, "收支账单数据为空！");
            return;
        }


        FulshData();
    }

    void selectSortType(List<DisplayBill> lists, int sortType) {
        if (lists == null) {
            MyToast.showMyToast(this, "渲染数据为空");
            return;
        }
        if (sortType == 1) {
            Collections.sort(lists, new Comparator<DisplayBill>() {
                @Override
                public int compare(DisplayBill o1, DisplayBill o2) {
                    if (o1.getAmoney() > o2.getAmoney()) {
                        return 1;
                    }
                    if (o1.getAmoney() == o2.getAmoney()) {
                        return 0;
                    }
                    return -1;
                }
            });
        } else if (sortType == 2) {
            Collections.sort(lists, new Comparator<DisplayBill>() {
                @Override
                public int compare(DisplayBill o1, DisplayBill o2) {
                    if (o1.getAmoney() < o2.getAmoney()) {
                        return 1;
                    }
                    if (o1.getAmoney() == o2.getAmoney()) {
                        return 0;
                    }
                    return -1;
                }
            });

        } else if (sortType == 3) {
            Collections.sort(lists, new Comparator<DisplayBill>() {
                @Override
                public int compare(DisplayBill o1, DisplayBill o2) {
                    //这里使用时间字段排序 如果要用其他字段直接从bean实体中取
                    return o1.getRecordTime().compareTo(o2.getRecordTime());
                    //上面使用的是降序排序，如果正序 直接使用o1-o2即可
                }
            });
        } else {

            Collections.sort(lists, new Comparator<DisplayBill>() {
                @Override
                public int compare(DisplayBill o1, DisplayBill o2) {
                    //这里使用时间字段排序 如果要用其他字段直接从bean实体中取
                    return o2.getRecordTime().compareTo(o1.getRecordTime());
                    //上面使用的是降序排序，如果正序 直接使用o1-o2即可
                }
            });
        }

    }

    /**
     *
     */
    public void FulshData() {
        selectSortType(displayBills, selectSortType);
        getUITaskDispatcher().asyncDispatch(() -> {
            //需要的数据
            if (displayBills == null) {
                MyToast.showMyToast(this, "渲染数据为空");
            }
            displayBillProvider = new DisplayBillProvider(displayBills, this);
            listContainer.setItemProvider(displayBillProvider);
            //点击进入详情页面
            listContainer.setItemClickedListener((container, component, i, id) -> {
                item = (DisplayBill) listContainer.getItemProvider().getItem(i);
                itemPosition = i;
                if (item == null) {
                    return;
                }
                //跳转
                Intent intent = new Intent();
                intent.setParam("Aid", item.getAid());
                presentForResult(new BillDetailsSlice(), intent, 1004);

            });
        });
    }

    //返回触发事件
    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == 1004) {
            if (resultIntent != null) {
                String op = resultIntent.getStringParam("op");
                if (op == null) {
                    return;
                }
                if (op.equals("del")) {
                    displayBills.remove(itemPosition);
                    //数据改变监听事件
                    listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                        @Override
                        public void onComponentBoundToWindow(Component component) {
                            // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                            // 建议在onComponentBoundToWindow监听或者其他事件监听中调用。
                            displayBillProvider.notifyDataSetItemRemoved(itemPosition);
                            // displayBillProvider.notifyDataChanged();
                        }

                        @Override
                        public void onComponentUnboundFromWindow(Component component) {
                        }
                    });
                } else if (op.equals("update")) {
                    String aid = resultIntent.getStringParam("aid");
                    try {
                        displayBill = MyUtil.queryDisplayBillByAid(this, aid);
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }
                    displayBills.remove(itemPosition);
                    displayBills.add(itemPosition, displayBill);
                    //数据改变监听事件
                    listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                        @Override
                        public void onComponentBoundToWindow(Component component) {
                            // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                            // 建议在onComponentBoundToWindow监听或者其他事件监听中调用。
//                            displayBillProvider.notifyDataSetItemRemoved(itemPosition);
//                            displayBillProvider.notifyDataSetItemRangeInserted(itemPosition, 1);
                            displayBillProvider.notifyDataSetItemChanged(itemPosition);
                        }

                        @Override
                        public void onComponentUnboundFromWindow(Component component) {
                        }
                    });
                } else {

                }


            }


        }
    }

    //展示账单的时间
    public void showPickTimeType(AbilityContext context) {
        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_billdate_select, null, false);
        //创建显示气窗
        RadioContainer radioContainer = (RadioContainer) parse.findComponentById(ResourceTable.Id_radiocontainer);
        Text time_Text = (Text) parse.findComponentById(ResourceTable.Id_select_time);
        CommonDialog dialog = new CommonDialog(this);
        dialog.setOffset(0, 10);
        dialog.setContentCustomComponent(parse);
        dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
        selectTimeType = 0;
        displaytime = null;
        dialog.show();
        radioContainer.setMarkChangedListener((container, i) -> {
            selectTimeType = i;
        });
        //点击按键
        time_Text.setClickedListener(component -> {
            if (selectTimeType == 1) {//按照日
                showPickDateConfirmTips(this, time_Text);
            } else if (selectTimeType == 2) {//按照月
                showSelectYearAndMonthList(time_Text);
            } else if (selectTimeType == 3) {//按照年
                showSelectYearList(time_Text);
            } else {//默认全部
                time_Text.setText("默认全部");
                displaytime = null;
                select_time.setText("默认全部");
            }

        });


        cancel.setClickedListener(c -> {
            dialog.destroy();
            MyToast.showMyToast(this, "已取消");

        });
        ok.setClickedListener(c -> {
            dialog.hide();
            try {
                displayBills = MyUtil.queryDisplayTotalBillAndArtime(this, displaytime);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }
            FulshData();
        });
    }

    //弹出日期dialog，选择日期
    public void showPickDateConfirmTips(Context context, Text selectedDateText) {
        CommonDialog commonDialog = new CommonDialog(context);
        Component parse = LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_date_layout_confirm, null, false);

        DatePicker datePicker = (DatePicker) parse.findComponentById(ResourceTable.Id_date_pick);
        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
        cancel.setClickedListener(c -> {
            commonDialog.destroy();
            MyToast.showMyToast(this, "已取消");

        });
        ok.setClickedListener(c -> {
            int dateYear, dateMonth, dateDay;
            dateYear = datePicker.getYear();
            dateMonth = datePicker.getMonth();
            dateDay = datePicker.getDayOfMonth();
            displaytime = DateUtils.getyyyyMMddFormatFromPicker(dateYear, dateMonth, dateDay);
            selectedDateText.setText(displaytime);
            select_time.setText(displaytime);
            commonDialog.remove();
        });


        commonDialog.setOffset(0, 10);
        commonDialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        commonDialog.setAlignment(LayoutAlignment.CENTER);
        commonDialog.setTransparent(true);
        commonDialog.setCornerRadius(25);
        commonDialog.setContentCustomComponent(parse);
        commonDialog.show();
    }


    public void showSelectYearList(Text text) {
        //布局加载
        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_select_year, null, false);

        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
        //选择器
        Picker picker = (Picker) parse.findComponentById(ResourceTable.Id_select_year_picker);
        ShapeElement shape = new ShapeElement();
        shape.setShape(ShapeElement.RECTANGLE);
        shape.setRgbColor(RgbColor.fromArgbInt(0xFF40E0D0));
        picker.setDisplayedLinesElements(shape, shape);
        //加载滑动数据
        String[] yearList = DateUtils.getSelectStatisticalYearList(5);
        picker.setMaxValue(yearList.length / 2);
        picker.setFormatter(i -> yearList[i]);

        picker.setSelectorItemNum(3);
        picker.setValue(yearList.length / 2);
        getUITaskDispatcher().asyncDispatch(() -> { //ui刷新线程显示

            //创建显示气窗
            CommonDialog dialog = new CommonDialog(this);
            dialog.setOffset(0, 10);
            dialog.setContentCustomComponent(parse);
            dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
            dialog.show();
            selectYearIndex = yearList.length / 2;
            picker.setValueChangedListener((picker1, oldi, newi) -> {
                selectYearIndex = newi;
            });
            cancel.setClickedListener(c -> {
                dialog.destroy();
                MyToast.showMyToast(this, "已取消");

            });
            ok.setClickedListener(c -> {
                displaytime = yearList[selectYearIndex];
                text.setText(displaytime);
                select_time.setText(displaytime);
                dialog.hide();
            });
        });
    }

    public void showSelectYearAndMonthList(Text text) {
        //布局加载
        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_select_year_month, null, false);

        //取消按钮
        Button cancel = (Button) parse.findComponentById(ResourceTable.Id_cancel);
        //确定按钮
        Button ok = (Button) parse.findComponentById(ResourceTable.Id_ok);
        //选择器
        Picker select_year = (Picker) parse.findComponentById(ResourceTable.Id_select_year_picker);
        Picker select_month = (Picker) parse.findComponentById(ResourceTable.Id_select_year_and_month_picker);
        ShapeElement shape = new ShapeElement();
        shape.setShape(ShapeElement.RECTANGLE);
        shape.setRgbColor(RgbColor.fromArgbInt(0xFF40E0D0));
        select_year.setDisplayedLinesElements(shape, shape);
        select_month.setDisplayedLinesElements(shape, shape);
        //加载滑动数据
        String[] yearList = DateUtils.getSelectStatisticalYearList(5);
        select_year.setMaxValue(yearList.length / 2);
        select_year.setFormatter(i -> yearList[i]);

        select_year.setSelectorItemNum(3);
        select_year.setValue(yearList.length / 2);

        String[] monthList = DateUtils.getSelectStatisticalMonthList();
        select_month.setMaxValue(monthList.length - 1);
        select_month.setFormatter(i -> monthList[i]);

        select_month.setSelectorItemNum(3);
        select_month.setValue(DateUtils.getCurrentMonth() - 1);

        //创建显示气窗
        CommonDialog dialog = new CommonDialog(this);
        dialog.setOffset(0, 10);
        dialog.setContentCustomComponent(parse);
        dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        dialog.show();
        selectYearIndex = yearList.length / 2;
        selectMonthIndex = DateUtils.getCurrentMonth() - 1;
        select_year.setValueChangedListener((picker1, oldi, newi) -> {
            selectYearIndex = newi;
        });

        select_month.setValueChangedListener((picker1, oldi, newi) -> {
            selectMonthIndex = newi;
        });

        cancel.setClickedListener(c -> {
            dialog.destroy();
            MyToast.showMyToast(this, "已取消");

        });
        ok.setClickedListener(c -> {
            displaytime = yearList[selectYearIndex] + "-" + monthList[selectMonthIndex];
            text.setText(displaytime);
            select_time.setText(displaytime);
            dialog.hide();

        });

    }

    //排序条件
    public void showPickSortType(AbilityContext context) {
        //分类类型
        getUITaskDispatcher().asyncDispatch(() -> {
            ListDialog listDialog = new ListDialog(context, ListDialog.SINGLE);
            listDialog.setCornerRadius(45);
            listDialog.getProvider();
            listDialog.setSize(1000, MATCH_CONTENT);
            String[] strings = {"模糊"};
            List<String> titles = new ArrayList<>();
            titles.add("默认排序");
            titles.add("记账金额正序");
            titles.add("记账金额倒序");
            titles.add("记账日期正序");
            titles.add("记账日期倒序");
            listDialog.setItems(strings);
            TitleProvider titleProvider = new TitleProvider(titles, this);
            listDialog.setProvider(titleProvider);
            listDialog.setButton(0, "取消", (iDialog, i) -> {
                iDialog.hide();
                MyToast.showMyToast(this, "已取消");

            });
            listDialog.setButton(1, "确定", (iDialog, i) -> {
                iDialog.hide();
                MyToast.showMyToast(this, "已确定");
            });
            //展示
            listDialog.show();
            //监听
            ((ListContainer) listDialog.getListContainer()).setItemSelectedListener((listContainer, component, i, l) -> {
                MyToast.showMyToast(this, "你选择了" + titles.get(i));
                select_condition.setText(titles.get(i));
                selectSortType = i;

                FulshData();
                //改变渲染数据
                listDialog.hide();

            });
        });
    }
}
